package com.lianjia.crawler;

import com.lianjia.crawler.model.HouseInfo;
import com.lianjia.crawler.utils.MongoDBUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Scanner;

/**
 * MongoDB查询工具，用于从MongoDB中查询房源信息
 */
public class MongoDBQuery {
    private static final Logger logger = LoggerFactory.getLogger(MongoDBQuery.class);
    
    // MongoDB连接字符串
    private static final String MONGODB_URI = "mongodb://localhost:27017";
    
    public static void main(String[] args) {
        try {
            logger.info("链家MongoDB查询工具启动");
            System.out.println("链家MongoDB查询工具启动");
            
            // 初始化MongoDB连接
            MongoDBUtils.init(MONGODB_URI);
            
            Scanner scanner = new Scanner(System.in);
            
            while (true) {
                System.out.println("\n请选择操作：");
                System.out.println("1. 按城市查询");
                System.out.println("2. 按价格区间查询");
                System.out.println("3. 按面积区间查询");
                System.out.println("4. 组合条件查询");
                System.out.println("0. 退出");
                
                System.out.print("请输入选项: ");
                String choice = scanner.nextLine().trim();
                
                if ("0".equals(choice)) {
                    break;
                }
                
                switch (choice) {
                    case "1":
                        queryByCity(scanner);
                        break;
                    case "2":
                        queryByPriceRange(scanner);
                        break;
                    case "3":
                        queryByAreaRange(scanner);
                        break;
                    case "4":
                        queryByCombinedConditions(scanner);
                        break;
                    default:
                        System.out.println("无效选项，请重新输入");
                }
            }
            
            // 关闭MongoDB连接
            MongoDBUtils.close();
            
            logger.info("查询工具已退出");
            System.out.println("查询工具已退出");
            
        } catch (Exception e) {
            logger.error("查询工具运行出错", e);
            System.out.println("查询工具运行出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 按城市查询
     */
    private static void queryByCity(Scanner scanner) {
        System.out.print("请输入城市名称: ");
        String cityName = scanner.nextLine().trim();
        
        System.out.print("请输入查询数量限制(默认10): ");
        String limitStr = scanner.nextLine().trim();
        int limit = limitStr.isEmpty() ? 10 : Integer.parseInt(limitStr);
        
        List<HouseInfo> results = MongoDBUtils.queryHouseInfo(cityName, null, null, null, null, limit);
        
        displayResults(results);
    }
    
    /**
     * 按价格区间查询
     */
    private static void queryByPriceRange(Scanner scanner) {
        System.out.print("请输入最低价格(万元，可为空): ");
        String minPriceStr = scanner.nextLine().trim();
        Double minPrice = minPriceStr.isEmpty() ? null : Double.parseDouble(minPriceStr);
        
        System.out.print("请输入最高价格(万元，可为空): ");
        String maxPriceStr = scanner.nextLine().trim();
        Double maxPrice = maxPriceStr.isEmpty() ? null : Double.parseDouble(maxPriceStr);
        
        System.out.print("请输入城市名称(可为空): ");
        String cityName = scanner.nextLine().trim();
        if (cityName.isEmpty()) {
            cityName = null;
        }
        
        System.out.print("请输入查询数量限制(默认10): ");
        String limitStr = scanner.nextLine().trim();
        int limit = limitStr.isEmpty() ? 10 : Integer.parseInt(limitStr);
        
        List<HouseInfo> results = MongoDBUtils.queryHouseInfo(cityName, minPrice, maxPrice, null, null, limit);
        
        displayResults(results);
    }
    
    /**
     * 按面积区间查询
     */
    private static void queryByAreaRange(Scanner scanner) {
        System.out.print("请输入最小面积(平方米，可为空): ");
        String minAreaStr = scanner.nextLine().trim();
        Double minArea = minAreaStr.isEmpty() ? null : Double.parseDouble(minAreaStr);
        
        System.out.print("请输入最大面积(平方米，可为空): ");
        String maxAreaStr = scanner.nextLine().trim();
        Double maxArea = maxAreaStr.isEmpty() ? null : Double.parseDouble(maxAreaStr);
        
        System.out.print("请输入城市名称(可为空): ");
        String cityName = scanner.nextLine().trim();
        if (cityName.isEmpty()) {
            cityName = null;
        }
        
        System.out.print("请输入查询数量限制(默认10): ");
        String limitStr = scanner.nextLine().trim();
        int limit = limitStr.isEmpty() ? 10 : Integer.parseInt(limitStr);
        
        List<HouseInfo> results = MongoDBUtils.queryHouseInfo(cityName, null, null, minArea, maxArea, limit);
        
        displayResults(results);
    }
    
    /**
     * 组合条件查询
     */
    private static void queryByCombinedConditions(Scanner scanner) {
        System.out.print("请输入城市名称(可为空): ");
        String cityName = scanner.nextLine().trim();
        if (cityName.isEmpty()) {
            cityName = null;
        }
        
        System.out.print("请输入最低价格(万元，可为空): ");
        String minPriceStr = scanner.nextLine().trim();
        Double minPrice = minPriceStr.isEmpty() ? null : Double.parseDouble(minPriceStr);
        
        System.out.print("请输入最高价格(万元，可为空): ");
        String maxPriceStr = scanner.nextLine().trim();
        Double maxPrice = maxPriceStr.isEmpty() ? null : Double.parseDouble(maxPriceStr);
        
        System.out.print("请输入最小面积(平方米，可为空): ");
        String minAreaStr = scanner.nextLine().trim();
        Double minArea = minAreaStr.isEmpty() ? null : Double.parseDouble(minAreaStr);
        
        System.out.print("请输入最大面积(平方米，可为空): ");
        String maxAreaStr = scanner.nextLine().trim();
        Double maxArea = maxAreaStr.isEmpty() ? null : Double.parseDouble(maxAreaStr);
        
        System.out.print("请输入查询数量限制(默认10): ");
        String limitStr = scanner.nextLine().trim();
        int limit = limitStr.isEmpty() ? 10 : Integer.parseInt(limitStr);
        
        List<HouseInfo> results = MongoDBUtils.queryHouseInfo(cityName, minPrice, maxPrice, minArea, maxArea, limit);
        
        displayResults(results);
    }
    
    /**
     * 显示查询结果
     */
    private static void displayResults(List<HouseInfo> results) {
        if (results.isEmpty()) {
            System.out.println("未找到符合条件的房源信息");
            return;
        }
        
        System.out.println("\n查询结果（共 " + results.size() + " 条）：");
        System.out.println("----------------------------------------------");
        
        for (int i = 0; i < results.size(); i++) {
            HouseInfo info = results.get(i);
            System.out.println((i + 1) + ". " + info.getTitle());
            System.out.println("   位置: " + info.getLocation());
            
            if (info.getPrice() != null) {
                String totalPrice = info.getPrice().getTotalPrice() != null ? info.getPrice().getTotalPrice() : "未知";
                String unitPrice = info.getPrice().getUnitPrice() != null ? info.getPrice().getUnitPrice() : "未知";
                System.out.println("   价格: " + totalPrice + " (" + unitPrice + ")");
            }
            
            if (info.getDetails() != null && !info.getDetails().isEmpty()) {
                System.out.println("   详情: " + info.getDetails());
            }
            
            System.out.println("   链接: " + info.getLink());
            System.out.println("----------------------------------------------");
        }
    }
} 